<!--
 * @Description: 标准任务编辑问卷调查类
 * @Author: liyujie
 * @Date: 2021/10/27
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/10/27
-->
<template>
    <div class="wrapper standard-task-edit">
        <div class="content-wrapper">
            <!-- header -->
            <div class="header">
                <div class="page-title">新建任务类型：问卷调查</div>
                <div class="steps-bar">
                    <div
                        v-for="(item,index) in 3"
                        :key="item"
                        class="steps-bar-item"
                        :class="{'is-active': step >= index}"
                    >
                        <div class="index-circle">
                            {{ item }}
                        </div>
                        <div class="text">
                            {{ item === 1 ? '问卷规则' : item === 2 ? '问卷内容' : '创建完成' }}
                        </div>
                    </div>
                </div>
                <div/>
            </div>
            <!-- /header -->

            <!--问卷规则-->
            <template v-if="step === 0">
                <el-form
                    :model="ruleForm"
                    :rules="rules"
                    ref="ruleForm"
                    label-width="110px"
                    :disabled="type === 'detail' || status == 1"
                >
                    <div class="form-wrapper">
                        <div class="form-title">
                            基本信息
                        </div>
                        <!--任务基本信息-->
                        <div class="form-content">
                            <el-form-item
                                label="绑定商家"
                                prop="shop_no"
                                key="shop_no"
                            >
                                <el-select
                                    v-model="ruleForm.shop_no"
                                    size="medium"
                                    clearable
                                    placeholder="请选择"
                                    style="width: 468px"
                                    filterable
                                    remote
                                    reserve-keyword
                                    :remote-method="getShopData"
                                >
                                    <el-option
                                        v-for="item in shopData"
                                        :key="item.shop_no"
                                        :label="item.shop_title"
                                        :value="item.shop_no"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item
                                label="任务标题"
                                prop="task_title"
                                key="task_title"
                                class="is-required"
                            >
                                <el-input
                                    v-model="ruleForm.task_title"
                                    size="medium"
                                    clearable
                                    placeholder="请输入任务标题"
                                    style="width: 468px"
                                    maxlength="20"
                                    show-word-limit
                                />
                            </el-form-item>
                            <el-form-item
                                label="领取时间"
                                class="is-required"
                            >
                                <div style="display: flex; align-items: center">
                                    <el-form-item
                                        prop="apply_start_time"
                                        key="apply_start_time"
                                    >
                                        <el-date-picker
                                            v-model="ruleForm.apply_start_time"
                                            type="datetime"
                                            default-time="00:00:00"
                                            size="medium"
                                            placeholder="请选择开始时间"
                                            style="width: 218px"
                                            value-format="timestamp"
                                        />
                                    </el-form-item>
                                    <span style="margin: 0 12px">-</span>
                                    <el-form-item
                                        prop="apply_end_time"
                                        key="apply_end_time"
                                    >
                                        <el-date-picker
                                            v-model="ruleForm.apply_end_time"
                                            type="datetime"
                                            placeholder="请选择结束时间"
                                            default-time="23:59:59"
                                            size="medium"
                                            style="width: 218px"
                                            value-format="timestamp"
                                        />
                                    </el-form-item>
                                </div>
                            </el-form-item>
                            <el-form-item
                                label="任务时间"
                                prop="accept_expire_in"
                                key="accept_expire_in"
                            >
                                <el-input
                                    v-model="ruleForm.accept_expire_in"
                                    size="medium"
                                    style="width: 218px"
                                    :disabled="ruleForm.accept_expire_in_type"
                                >
                                    <template slot="append">小时</template>
                                </el-input>
                                <el-checkbox
                                    v-model="ruleForm.accept_expire_in_type"
                                    label="不限制"
                                    style="margin-left: 12px"
                                />
                                <span class="form-item-tips">设置任务时间，代表该任务需要用户多久完成，超时则自动放弃</span>
                            </el-form-item>
                            <el-form-item
                                label="任务单价"
                                prop="task_price"
                                key="task_price"
                                class="is-required"
                            >
                                <el-input
                                    v-model="ruleForm.task_price"
                                    size="medium"
                                    clearable
                                    placeholder="请输入单个任务奖励金额"
                                    style="width: 284px"
                                    @change="getTaskMoney(ruleForm.task_price)"
                                >
                                    <span
                                        slot="suffix"
                                        style="margin-right: 6px"
                                    >元/个</span>
                                </el-input>
                                <span
                                    class="form-item-tips"
                                    v-if="stuagent_task_money"
                                >用户端展示金额为{{ stuagent_task_money }}元</span>
                            </el-form-item>
                            <el-form-item
                                label="任务总数"
                                prop="all_count"
                                key="all_count"
                                class="is-required"
                            >
                                <el-input-number
                                    v-model="ruleForm.all_count"
                                    placeholder="请输入任务总数"
                                    controls-position="right"
                                    :step="1"
                                    step-strictly
                                    :min="-1"
                                    size="medium"
                                    style="width: 284px"
                                />
                                <span class="form-item-tips">-1为不限制</span>
                            </el-form-item>
                            <el-form-item
                                label="支持重复领取"
                                class="is-required"
                            >
                                <el-radio-group
                                    v-model="ruleForm.accept_limit_count"
                                >
                                    <el-radio :label="-1">是</el-radio>
                                    <el-radio :label="1">否</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-form-item
                                label="任务简介"
                                prop="task_intro"
                                key="task_intro"
                                class="is-required"
                            >
                                <div class="desc-wrapper">
                                    <el-input
                                        v-model="ruleForm.task_intro"
                                        type="textarea"
                                        placeholder="请输入任务介绍"
                                        style="max-width: 886px"
                                        :autosize="{ minRows: 8}"
                                        maxlength="1000"
                                        show-word-limit
                                    />
                                    <div class="desc-material">
                                        <div class="desc-title">
                                            <div class="title">示例展示（非必填）：</div>
                                            <el-radio-group
                                                v-model="ruleForm.task_intro_material_type"
                                                style="margin-top: 2px"
                                            >
                                                <el-radio label="image">图片</el-radio>
                                                <el-radio label="video">视频</el-radio>
                                            </el-radio-group>
                                        </div>
                                        <div class="desc-content">
                                            <video-upload
                                                v-model="ruleForm.task_intro_material.video_path"
                                                action="/student/task_stuagent%5Cget_upload_video_auth"
                                                request-cover="/student/task_stuagent%5Cget_video_cover"
                                                request-preview="/student/task_stuagent%5Cget_video_preview_url"
                                                v-if="ruleForm.task_intro_material_type === 'video'"
                                                style=" margin-right: 24px"
                                                ref="videoUpload"
                                                limit-type="MB"
                                                :limit="200"
                                                @after-upload="(e) => {ruleForm.task_intro_material.video_cover = e.video_cover}"
                                            />
                                            <image-upload-multiple
                                                v-model="ruleForm.task_intro_material.images"
                                                limit-type="MB"
                                                :limit="1"
                                                :max="9"
                                                v-if="ruleForm.task_intro_material_type === 'image'"
                                                :type="status == 1 ? 'detail' : ''"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item
                                label="导师微信"
                                prop="task_qrcode"
                                key="task_qrcode"
                            >
                                <image-upload
                                    v-model="ruleForm.task_qrcode"
                                    limit-type="MB"
                                    :limit="1"
                                    :type="status == 1 ? 'detail' : ''"
                                    tips="图片大小270*270px，小于1MB"
                                />
                            </el-form-item>
                        </div>
                        <div class="form-title">
                            领取用户限制
                        </div>
                        <div class="form-content">
                            <el-form-item label="精英等级限制">
                                <el-checkbox-group v-model="ruleForm.allow_agent_levels">
                                    <el-checkbox
                                        v-for="item in 6"
                                        :key="item"
                                        :label="item - 1"
                                    >
                                        E{{ item - 1 }}
                                    </el-checkbox>
                                </el-checkbox-group>
                                <el-checkbox
                                    v-model="ruleForm.show_only_for_trial_stuagent"
                                    :true-label="1"
                                    :false-label="0"
                                >
                                    仅体验账号可见
                                </el-checkbox>
                                <span class="form-item-tips">注：不勾选，所有用户都看得到</span>
                            </el-form-item>
                            <el-form-item label="城市区域限制">
                                <el-cascader
                                    v-model="ruleForm.binding_school_ids"
                                    :options="schoolOptions"
                                    style="width: 284px"
                                    collapse-tags
                                    clearable
                                    size="medium"
                                    :disabled="type === 'detail'"
                                    :props="{
                                        multiple: true,
                                        label: 'name',
                                        value: 'id',
                                        emitPath: false
                                    }"
                                    @change="$forceUpdate()"
                                />
                                <span class="form-item-tips">非必填，不填写默认所有学校的用户可以领取</span>
                            </el-form-item>
                            <el-form-item label="用户性别">
                                <el-select
                                    v-model="ruleForm.sex"
                                    size="medium"
                                    style="width: 152px"
                                >
                                    <el-option
                                        label="不限"
                                        :value="0"
                                    />
                                    <el-option
                                        label="男"
                                        :value="1"
                                    />
                                    <el-option
                                        label="女"
                                        :value="2"
                                    />
                                </el-select>
                            </el-form-item>
                        </div>
                        <div class="form-title">
                            步骤引导
                        </div>
                        <div class="form-content">
                            <el-form-item
                                label="步骤引导"
                                class="is-required"
                            >
                                <div class="steps-view">
                                    <div
                                        class="step-item"
                                        v-for="(item, index) in ruleForm.guide"
                                        :key="index"
                                    >
                                        <div class="step-item__header">
                                            <div class="step-item__header__title">步骤{{ numberChinese(index + 1) }}</div>
                                            <el-button
                                                type="text"
                                                :disabled="ruleForm.guide.length <= 1"
                                                @click="deleteStepItem(index)"
                                            >删除</el-button>
                                        </div>
                                        <div class="step-item__content">
                                            <el-form-item
                                                :prop="`guide[${index}].content`"
                                                :rules="rules.guide.content"
                                                key="guide_content"
                                                style="margin-bottom: 12px"
                                            >
                                                <div class="el-form-item__label">步骤引导内容</div>
                                                <el-input
                                                    v-model="item.content"
                                                    type="textarea"
                                                    placeholder="请输入步骤引导内容"
                                                    :autosize="{ minRows: 4}"
                                                    maxlength="500"
                                                    show-word-limit
                                                />
                                            </el-form-item>
                                            <el-form-item
                                                :prop="`guide[${index}].images`"
                                                :rules="rules.guide.images"
                                                key="guide_image"
                                                class="no-required"
                                            >
                                                <div
                                                    class="desc-material"
                                                    style="padding: 18px 0 0 0"
                                                >
                                                    <div class="desc-title">
                                                        <div class="title">步骤示例展示：</div>
                                                        <el-radio-group
                                                            v-model="item.type"
                                                            style="margin-top: 2px"
                                                            @change="changeDescType(item)"
                                                        >
                                                            <el-radio label="image">图片</el-radio>
                                                            <el-radio label="video">视频</el-radio>
                                                        </el-radio-group>
                                                        <span class="desc-tips">建议宽度750px，建议大小不超过1MB，支持jpg、jpeg、png；</span>
                                                    </div>
                                                    <div class="desc-content">
                                                        <video-upload
                                                            v-model="item.video_path"
                                                            action="/student/task_stuagent%5Cget_upload_video_auth"
                                                            request-cover="/student/task_stuagent%5Cget_video_cover"
                                                            request-preview="/student/task_stuagent%5Cget_video_preview_url"
                                                            v-if="item.type === 'video'"
                                                            style=" margin-right: 24px"
                                                            :ref="`videoUploadStep${index}`"
                                                            limit-type="MB"
                                                            :limit="200"
                                                            @after-upload="(e) => {item.video_cover = e.video_cover}"
                                                        />
                                                        <image-upload-multiple
                                                            v-model="item.images"
                                                            limit-type="MB"
                                                            :limit="1"
                                                            :max="9"
                                                            v-if="item.type === 'image'"
                                                            :type="status == 1 ? 'detail' : ''"
                                                        />
                                                    </div>
                                                </div>
                                            </el-form-item>
                                        </div>
                                    </div>
                                    <div
                                        class="add-btn"
                                        @click="addStepItem"
                                        v-if="status != 1"
                                    >
                                        <i class="el-icon-plus"/>
                                        添加步骤
                                    </div>
                                </div>
                            </el-form-item>
                        </div>
                        <div class="form-title">
                            常见问题FAQ
                            <span class="form-title-tips">
                                学生经常遇到的问题，以及对应的问题解决方案
                            </span>
                        </div>
                        <div class="form-content">
                            <div class="question-view">
                                <div
                                    class="question-item"
                                    v-for="(item, index) in ruleForm.faq"
                                    :key="index"
                                >
                                    <el-form-item :label="`常见问题${index + 1}`">
                                        <el-row>
                                            <el-col :span="23">
                                                <el-input
                                                    v-model="item.title"
                                                    size="medium"
                                                    clearable
                                                    placeholder="请输入常见问题"
                                                />
                                            </el-col>
                                            <el-col :span="1">
                                                <el-button
                                                    type="text"
                                                    style="margin-left: 12px"
                                                    :disabled="ruleForm.faq.length === 1"
                                                    @click="deleteQuestionItem(index)"
                                                >删除</el-button>
                                            </el-col>
                                        </el-row>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-input
                                            v-model="item.desc"
                                            type="textarea"
                                            placeholder="请输入解决方法"
                                            :autosize="{ minRows: 4}"
                                        />
                                    </el-form-item>
                                    <el-form-item
                                        v-if="status != 1"
                                    >
                                        <div
                                            class="add-btn"
                                            style="margin-top: 0;"
                                            v-if="index === ruleForm.faq.length - 1"
                                            @click="addQuestionItem"
                                        >
                                            <i class="el-icon-plus"/>
                                            添加常见问题
                                        </div>
                                    </el-form-item>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="operating-view">
                        <el-button
                            size="medium"
                            @click="handleRoute('standardTaskList')"
                        >
                            返回
                        </el-button>
                        <el-button
                            size="medium"
                            type="primary"
                            @click="nextStep"
                        >
                            下一步
                        </el-button>
                    </div>
                </el-form>
            </template>

            <!--问卷内容编辑-->
            <template v-if="step === 1">
                <div class="question-wrapper">
                    <questionnaire-edit
                        :title="ruleForm.task_title"
                        v-model="ruleForm.submit_config"
                        ref="questionnaireEdit"
                        @prev="handlePrev"
                        @submit="beforeSubmit($event)"
                    />
                </div>
            </template>

            <!--创建完成展示页面-->
            <template v-if="step === 2">
                <div class="result-wrapper">
                    创建完成
                </div>
            </template>
        </div>
        <!-- 图片预览 -->
        <img-preview ref="preview" />
    </div>
</template>

<script>
import { back } from '@/mixin/back';
import { numberChinese } from "@/assets/js/utils";
import { deepClone, uuid } from "@/assets/js/utils";
import ImgPreview from "@/components/common/img-preview";
import ImageUpload from "@/components/common/image-upload";
import ImageUploadMultiple from "@/components/common/image-upload-multiple";
import VideoUpload from "@/components/common/video-upload";
import QuestionnaireEdit from "@/components/standard-task/questionnaire-edit";

// 步骤数据模型
const stepModel = {
    content: '',
    images: [],
    type: 'image',
    video_path: '',
    video_cover: ''
};
// FAQ数据模型
const questionModel = {
    title: '',
    desc: ''
};
const numberReg = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/;

export default {
    name: 'StandardTaskQuestionnaireEdit',
    mixins: [back],
    components: {
        QuestionnaireEdit,
        VideoUpload, ImageUploadMultiple, ImageUpload, ImgPreview},
    data() {
        const checkEndTime = (rule, value, callback) => {
            if(value > this.ruleForm.apply_start_time) {
                callback();
            } else {
                callback(new Error('结束时间不能小于开始时间'));
            }
        };

        return {
            type: 'add',
            status: '',
            step: 0,
            ruleForm: {
                // 编辑时任务编号
                task_no: '',
                // 任务类型
                task_category: 8,
                // 精英多选模式
                agent_level_limit_type: 1,
                // 绑定商家编号
                shop_no: '',
                // 任务标题
                task_title: '',
                // 开始时间
                apply_start_time: '',
                // 结束时间
                apply_end_time: '',
                // 任务时间
                accept_expire_in: '',
                accept_expire_in_type: false,
                // 任务单价
                task_price: '',
                // 任务总数
                all_count: undefined,
                // 是否重复领取
                accept_limit_count: -1,

                // 任务简介 需修改支持图片视频
                task_intro: '',
                task_intro_material_type: 'image',
                task_intro_material: {
                    video_path: '',
                    video_cover: '',
                    images: []
                },
                // 导师微信
                task_qrcode: '',
                // 精英等级多选模式
                allow_agent_levels: [],
                // 仅体验账号可见
                show_only_for_trial_stuagent: 0,
                // 学校限制
                binding_school_ids: [],
                // 性别
                sex: 0,
                // 常见问题
                faq: [deepClone(questionModel)],
                // 步骤引导
                guide: [deepClone(stepModel)],
                // 问卷表单
                submit_config: [],
            },
            rules: {
                shop_no: [
                    {required: false, message: '请选择绑定商家', trigger: 'change'}
                ],
                task_title: [
                    {required: true, message: '请填写任务标题', trigger: 'blur'}
                ],
                apply_start_time: [
                    {required: true, message: '请选择开始时间', trigger: 'change'},
                ],
                apply_end_time: [
                    {required: true, message: '请选择结束时间', trigger: 'change'},
                    { validator: checkEndTime, trigger: 'change' }
                ],
                accept_expire_in: [
                    {pattern: /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/, message: '任务时间必须为整数', trigger: 'blur'}
                ],
                task_price: [
                    {required: true, message: '请填写任务单价', trigger: 'blur'},
                    {pattern: numberReg, message: '任务单价必须为数字', trigger: 'blur'},
                ],
                all_count: [
                    {required: true, message: '请填写任务总数', trigger: 'blur'},
                ],
                task_qrcode: [
                    {required: false, message: '请上传导师微信', trigger: 'change'}
                ],
                task_intro: [
                    {required: true, message: '请填写任务简介', trigger: 'blur'}
                ],
                guide: {
                    content: [
                        {required: true, message: '请填写步骤引导内容', trigger: 'blur'}
                    ],
                    images: [
                        {required: false, message: '请上传步骤示意图', trigger: 'change'}
                    ],
                },

            },
            schoolOptions: [],
            shopData: [],
            // 获取的计算任务奖励金额
            stuagent_task_money: '',
            // 预览二维码
            previewQrcode: '',
            previewVisible: false,
            loading: false,
            authResult: {}
        };
    },
    computed: {},
    watch: {},
    mounted() {
        this.init();
        this.getSchoolTree();
    },
    methods: {
        numberChinese,

        /**
         * @description 获取店铺数据
         */
        getShopData(query) {
            this.$post('/student/shop%5Cget_shop_list_for_select', {
                keyword: query
            }, res => {
                if (res.code === 1) {
                    this.shopData = res.data.list;
                } else {
                    this.$notify({
                        title: '提示',
                        message: res.msg,
                        type: 'warning'
                    });
                }
            });
        },

        /**
         * @description 页面初始化
         */
        init() {
            let query = this.$route.query;

            this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '工作'}, {
                title: '平台标准任务',
                path: '/student/standard-task-list'
            }, {title: query.type === 'edit' ? '编辑任务' : query.type === 'add' ? '新建任务' : '查看任务'}]);
            this.authResult = this.$route.meta.authResult;

            this.type = query.type;
            this.status = query.status;
            // 编辑或查看时
            if (query.type === 'edit' || query.type === 'detail') {
                this.ruleForm.task_no = query.task_no;
                this.getDetailData();
            }

            if (query.type === 'copy') {
                this.type = 'add';
                this.ruleForm.task_no = query.task_no;
                this.getDetailData();
            }
        },

        /**
         * @description 获取省/市/学校三级联动
         */
        getSchoolTree () {
            this.$post('/student/local_info%5Cschool_tree',{},resp => {
                if (resp.code === 1) {
                    this.schoolOptions = resp.data.tree;
                }
            });
        },

        /**
         * @description 获取数据
         */
        getDetailData() {
            this.tableLoading = true;
            let params = {
                task_no: this.ruleForm.task_no
            };

            this.$post('/student/task_stuagent%5Cget', params, res => {
                if (res.code === 1) {
                    let query = this.$route.query;
                    let data = res.data;

                    if (query.type === 'copy') {
                        data.task_no = '';
                    } else {
                        data.task_no = this.$route.query.task_no;
                    }
                    // 处理时间
                    data.apply_start_time = data.apply_start_time * 1000;
                    data.apply_end_time = data.apply_end_time * 1000;

                    // faq
                    if(!data.faq || !data.faq.length) {
                        data.faq = [deepClone(questionModel)];
                    }
                    this.getTaskMoney(data.task_price);

                    // 任务时间处理
                    if(data.accept_expire_in === -1 || !data.accept_expire_in) {
                        data.accept_expire_in_type = true;
                        data.accept_expire_in = '';
                    } else {
                        data.accept_expire_in_type = false;
                    }
                    // 任务说明素材回显
                    if(data.task_intro_material) {
                        if(data.task_intro_material.images && data.task_intro_material.images.length) {
                            data.task_intro_material_type = 'image';
                            data.task_intro_material.video_path = '';
                            data.task_intro_material.video_cover = '';
                        } else {
                            data.task_intro_material_type = 'video';
                            data.task_intro_material.images = [];
                            setTimeout(() => {
                                if(this.$refs.videoUpload && data.task_intro_material.video_path) {
                                    this.$refs.videoUpload.setData(data.task_intro_material.video_path);
                                }
                            });
                        }
                    } else {
                        data.task_intro_material_type = 'image';
                        data.task_intro_material = {
                            video_path: '',
                            video_cover: '',
                            images: []
                        };
                    }

                    data.guide.forEach((item, index) => {
                        if(!(item.images && item.images.length) && !item.video_path) {
                            item.type = 'image';
                            item.images = [];
                            item.video_path = '';
                            item.video_cover = '';
                        } else if(item.images && item.images.length) {
                            item.type = 'image';
                            item.video_cover = '';
                            item.video_path = '';
                        } else if (item.video_path) {
                            item.type = 'video';
                            item.images = [];
                            setTimeout(() => {
                                if(this.$refs[`videoUploadStep${index}`] && item.video_path) {
                                    this.$refs[`videoUploadStep${index}`][0].setData(item.video_path);
                                }
                            });
                        }
                    });

                    // 处理submit_config
                    data.submit_config.forEach(item => {
                        if(item.type === 12) {
                            item.title = '';
                            item.has_intro = '';
                            item.intro = '';
                            item.required = '';
                            item.hint = '';
                            item.disabled = '';
                            item.length_type = '';
                            item.value_length_min = '';
                            item.value_length_max = '';
                            item.pagination_stay_time_type = item.pagination_stay_time === -1 ? 0 : 1;
                            item.value_validation_type = 0;
                            item.value_validation_rule = '';
                            item.classes = {
                                overflow_fold: 0
                            };
                            item.name = '';
                            item.default = {};
                            item.options = [];
                        } else {
                            item.isHover = false;
                            item.isActive = false;
                            item.has_intro = item.intro ? 1 : 0;
                            item.id = uuid();
                            item.pagination_stay_time_type = item.pagination_stay_time === -1 ? 0 : 1;
                            if(item.options) {
                                item.options.forEach(option => {
                                    option.isHover = false;
                                    option.isActive = false;
                                    option.has_intro = option.intro ? 1 : 0;
                                    option.length_type = option.edit_content_length_max === -1 ? 0 : 1;
                                });
                            }
                        }
                    });
                    this.getShopData(data.shop_title);
                    this.ruleForm = data;
                } else {
                    this.$notify({
                        title: '提示',
                        message: res.msg,
                        type: 'warning'
                    });
                }
                this.tableLoading = false;
            });
        },

        /**
         * 路由跳转
         * @param routeName
         * @param query
         */
        handleRoute(routeName, query) {
            this.$router.push({
                name: routeName,
                query
            });
        },

        /**
         * 预览图片
         * @param   {String}    images      //单图预览
         * @param   {Array}     images      //多图预览
         * @param index
         */
        showPreview(images, index) {
            if (images && Object.prototype.toString.call(images) == '[object String]') {
                this.$refs.preview.show([
                    images
                ]);
            } else if (images && Object.prototype.toString.call(images) == '[object Array]') {
                this.$refs.preview.show(images, index);
            } else {
                this.$message({
                    type: 'warning',
                    message: '图片类型错误'
                });
            }
        },

        /**
         * 删除步骤
         * @param index
         */
        deleteStepItem(index) {
            this.ruleForm.guide.splice(index, 1);
        },

        /**
         * 添加步骤
         */
        addStepItem() {
            if(this.ruleForm.guide.length >= 20) {
                this.$message.warning('最多不超过20个步骤');
                return;
            }
            this.ruleForm.guide.push(deepClone(stepModel));
        },

        /**
         * 删除常见问题
         * @param index
         */
        deleteQuestionItem(index) {
            this.ruleForm.faq.splice(index, 1);
        },

        /**
         * 添加常见问题
         */
        addQuestionItem() {
            this.ruleForm.faq.push(deepClone(questionModel));
        },

        /**
         * 下一步
         */
        nextStep() {
            this.$refs['ruleForm'].validate((valid) => {
                if (valid) {
                    this.step = 1;
                } else {
                    // 校验不通过
                    if(document.getElementsByClassName('el-form-item__error').length > 0){
                        this.$notify.warning({
                            title: '提示',
                            message: document.getElementsByClassName('el-form-item__error')[0].innerText
                        });
                    }
                    return false;
                }
            });
        },

        /**
         * @description 提交数据处理
         */
        beforeSubmit(task_status, type) {
            let params = deepClone(this.ruleForm);

            // 处理时间
            params.apply_start_time = params.apply_start_time / 1000;
            params.apply_end_time = params.apply_end_time / 1000;
            params.task_status = task_status;
            let faq = params.faq.filter(item => {
                return item.title !== '' || item.desc !== '';
            });

            // 处理步骤引导
            params.guide_json = JSON.stringify(params.guide);
            // 处理常见问题
            params.faq_json = JSON.stringify(faq);
            // 精英等级
            params.allow_agent_levels = params.allow_agent_levels.join();
            // 学校限制
            params.binding_school_ids = params.binding_school_ids.join();
            // 任务时间
            if(params.accept_expire_in_type || !params.accept_expire_in) {
                params.accept_expire_in = -1;
            }

            // 问卷表单不能为空
            if(!params.submit_config.length) {
                this.$notify({
                    title: '提示',
                    type: 'warning',
                    message: '反馈内容不能为空'
                });
                return false;
            }
            params.submit_config_json = JSON.stringify(params.submit_config);

            // 处理任务介绍的素材
            if(params.task_intro_material_type === 'image') {
                params.task_intro_material.video_path = '';
                params.task_intro_material.video_cover = '';
            } else {
                params.task_intro_material.images = [];
            }
            if(params.task_intro_material.video_path === '' && params.task_intro_material.images.length === 0) {
                params.task_intro_material = null;
            }
            params.task_intro_material = JSON.stringify(params.task_intro_material);

            delete params.submit_config;
            delete params.guide;
            delete params.faq;
            if(type === 'preview') {
                // 预览
                this.handlePreview(params);
            } else {
                // 保存
                this.handleSubmit(params);
            }
        },

        /**
         * 提交数据
         * @param params
         */
        handleSubmit(params) {
            this.loading = true;
            this.$post('/student/task_stuagent%5Csave', params, resp => {
                if (resp.code === 1) {
                    this.$notify({
                        title: '提示',
                        message: '保存成功',
                        duration: 2000,
                        type: 'success'
                    });
                    this.handleRoute('standardTaskList');
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        duration: 2000,
                        type: 'warning'
                    });
                }
                this.loading = false;
            });
        },

        /**
         * 预览
         * @param params
         */
        handlePreview(params) {
            this.$post('/student/task_stuagent%5Cpreview', params, resp => {
                if (resp.code === 1) {
                    let base = this.$baseUrl;
                    let ticket = localStorage.getItem('sessionTicket');

                    this.previewQrcode = `${base}/__local/common%5Cqrcode?content=${resp.data.preview_url}&__ticket=${ticket}`;
                    this.previewVisible = true;
                } else {
                    this.$notify({
                        title: '提示',
                        message: resp.msg,
                        type: 'warning',
                        duration: 2000
                    });
                }
            });
        },

        /**
         * 获取任务分佣金额
         * @param task_money
         */
        async getTaskMoney(task_money) {
            if(!task_money) {
                this.stuagent_task_money = 0;
                return;
            }
            this.stuagent_task_money = await this.getUserMoney(task_money);
        },

        /**
         * 获取计算用户显示金额
         * @param money
         * @returns {Promise<unknown>}
         */
        getUserMoney(money) {
            return new Promise((resolve, reject) => {
                this.$post('/student/task_stuagent%5Cget_stuagent_task_money', {task_money: money}, resp => {
                    if (resp.code === 1) {
                        resolve(resp.data.stuagent_task_money);
                    } else {
                        this.$notify({
                            title: '提示',
                            message: resp.msg,
                            duration: 2000,
                            type: 'warning'
                        });
                    }
                });
            });
        },

        /**
         * 改变图片或者视频类型
         * @param item
         */
        changeDescType(item) {
            item.video_path = '';
            item.video_cover = '';
            item.images = [];
        },

        /**
         * 处理返回上一页
         */
        handlePrev() {
            this.step = 0;
            this.ruleForm.guide.forEach((item, index) => {
                setTimeout(() => {
                    if(this.$refs[`videoUploadStep${index}`] && item.video_path) {
                        this.$refs[`videoUploadStep${index}`][0].setData(item.video_path);
                    }

                    if(this.$refs.videoUpload && this.ruleForm.task_intro_material.video_path) {
                        this.$refs.videoUpload.setData(this.ruleForm.task_intro_material.video_path);
                    }
                });
            });
        }
    }
};
</script>

<style lang="less" scoped>
.wrapper {
    width: 100%;

    .content-wrapper {
        display: flex;
        height: calc(100% - 24px);
        flex-direction: column;
        position: relative;
        margin: 12px;

        /*header*/

        .header {
            height: 66px;
            background: #FFFFFF;
            padding: 0 32px;
            display: flex;
            align-items: center;
            margin-bottom: 12px;
            flex-shrink: 0;
            position: relative;

            .page-title {
                font-size: 18px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #333333;
                line-height: 20px;
            }
            .steps-bar {
                display: flex;
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
                &-item {
                    display: flex;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #999999;
                    line-height: 20px;
                    &:not(&:first-of-type) {
                        margin-left: 128px;
                        position: relative;
                        &::before {
                            content: "";
                            position: absolute;
                            width: 80px;
                            height: 2px;
                            background: #DADFE6;
                            border-radius: 1px;
                            left: -104px;
                            top: 50%;
                            transform: translateY(-50%);
                        }
                    }
                    .index-circle {
                        width: 20px;
                        height: 20px;
                        border-radius: 50%;
                        font-size: 12px;
                        font-family: SFCompactDisplay-Medium, SFCompactDisplay;
                        font-weight: 500;
                        color: #FFFFFF;
                        line-height: 12px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        background: #DADFE6;
                        margin-right: 8px;
                    }
                    &.is-active {
                        color: #333;
                        .index-circle {
                            background: #20A0FF;
                        }
                        &:not(&:first-of-type) {
                            &::before {
                                background: #20A0FF;
                            }
                        }
                    }
                }
            }
        }
        // 第一步基础问卷规则
        .el-form {
            flex: 1;
            overflow-y: auto;
            padding: 32px;
            background-color: #ffffff;
            &::-webkit-scrollbar {
                width: 6px;
                height: 6px;
            }
            .form-wrapper {
                background: #FBFBFB;
                border: 1px solid #EEEEEE;
                padding: 32px;
                .form-title {
                    font-size: 16px;
                    font-family: PingFangSC-Semibold, PingFang SC;
                    font-weight: 600;
                    color: #333333;
                    line-height: 16px;
                    padding-bottom: 12px;
                    border-bottom: 1px solid #E9E9E9;
                    margin-bottom: 24px;
                    &-tips {
                        font-size: 14px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #C2C2C2;
                        margin-left: 12px;
                    }
                }
                .form-content {
                    margin-bottom: 32px;
                    .steps-view {
                        .step-item {
                            background: #F7F7F7;
                            border-radius: 2px;
                            border: 1px solid #DCDFE6;
                            margin-bottom: 12px;
                            &__header {
                                height: 44px;
                                background: #F0F0F0;
                                border-radius: 2px 2px 0 0;
                                border-bottom: 1px solid #DCDFE6;
                                display: flex;
                                align-items: center;
                                justify-content: space-between;
                                font-size: 16px;
                                font-family: PingFangSC-Medium, PingFang SC;
                                font-weight: 500;
                                color: #333333;
                                padding: 0 32px;
                                &__title {
                                    position: relative;
                                    &::before {
                                        content: "";
                                        display: block;
                                        position: absolute;
                                        width: 4px;
                                        height: 14px;
                                        background: #FF3030;
                                        left: -12px;
                                        top: 50%;
                                        transform: translateY(-50%);
                                    }
                                }
                            }
                            &__content {
                                padding: 24px 32px;
                                .label-tips {
                                    font-size: 14px;
                                    font-family: PingFangSC-Regular, PingFang SC;
                                    font-weight: 400;
                                    color: #999999;
                                    margin-left: 12px;
                                }
                            }
                        }
                    }
                    .add-btn {
                        height: 36px;
                        background: #F2FAFF;
                        border-radius: 4px;
                        border: 1px dashed #20A0FF;
                        font-size: 14px;
                        font-family: PingFangSC-Medium, PingFang SC;
                        font-weight: 500;
                        color: #20A0FF;
                        line-height: 14px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        cursor: pointer;
                        margin-top: 24px;
                        .el-icon-plus {
                            margin-right: 10px;
                        }
                    }
                    .form-item-tips {
                        font-size: 14px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #C2C2C2;
                        margin-left: 12px;
                    }
                    .desc-wrapper {
                        background: #FBFBFB;
                        border-radius: 4px;
                        border: 1px solid #CAD0DC;
                        max-width: 886px;
                        /deep/ .el-textarea {
                            &__inner {
                                background: #FBFBFB;
                                border: 0;
                                border-bottom: 1px solid #CAD0DC;
                                border-radius: 4px 4px 0 0;
                                font-size: 14px;
                                font-family: PingFangSC-Regular, PingFang SC;
                                line-height: 22px;
                            }
                            .el-input__count {
                                background: #FBFBFB;
                            }
                        }
                    }
                    .desc-material {
                        padding: 18px 20px;
                        .desc-title {
                            display: flex;
                            align-items: center;
                            font-size: 14px;
                            font-family: PingFangSC-Regular, PingFang SC;
                            font-weight: 400;
                            color: #333333;
                            line-height: 22px;
                            .title {
                                margin-right: 8px;
                            }
                            .desc-tips {
                                font-size: 12px;
                                font-family: PingFangSC-Regular, PingFang SC;
                                font-weight: 400;
                                color: #999999;
                                line-height: 14px;
                                margin-left: 22px;
                            }
                        }
                        .desc-content {
                            margin-top: 20px;
                        }
                    }
                }
            }
            .operating-view {
                padding: 32px 56px 52px;
                display: flex;
                align-items: center;
                justify-content: center;
                .el-button {
                    width: 120px;
                    margin-right: 36px;
                }
            }
        }

        // 第二步问卷编辑
        .question-wrapper {
            flex: 1;
            overflow-x: auto;
            overflow-y: hidden;
            &::-webkit-scrollbar {
                width: 6px;
                height: 6px;
            }
        }

        // 第三步创建完成
        .result-wrapper {
            flex: 1;
            overflow-y: auto;
            padding: 32px;
            background-color: #ffffff;
        }

    }
    /deep/ .el-form {
        .el-form-item__label {
            color: #333;
        }
        .is-required {
            .el-form-item__label {
                &:before {
                    content: "*";
                    display: inline-block;
                    color: #F56C6C;
                    margin-right: 4px;
                }
            }
        }
        .no-required {
            .el-form-item__label {
                &:before {
                    display: none;
                }
            }
        }
        .el-input-number {
            .el-input__inner {
                text-align: left;
            }
        }
        .el-input__suffix {
            display: flex;
            align-items: center;
        }
    }
    /deep/ .el-dialog__header {
        padding-top: 10px;
        box-shadow:0 1px 0 0 rgba(233,233,233,1);
        display: flex;
        align-items: center;
        background: #FAFAFA;
        border-radius: 4px 4px 0 0;
        .el-dialog__title {
            font-weight: 500;
            color: #333;
            font-size: 14px;
        }
        .el-icon-close:before {
            color: rgb(194,194,194);
            font-size: 17px;
            font-weight: bold;
        }
        .el-dialog__headerbtn {
            top: 14px;
        }
    }
    .dialog-footer {
        display: flex;
        justify-content: center;
    }
    /deep/ .el-textarea__inner {
        resize: none;
    }

    /deep/ .pic-view {
        align-items: flex-end;
        display: flex;
        .tips {
            margin-bottom: 24px;
        }
    }
    .data-table {
        ::-webkit-scrollbar {
            width: 6px;
            height: 6px;
        }
    }
}
</style>
<style lang="less">
.wrapper.standard-task-edit {
    .el-table.standard-task-edit__table {
        th {
            background: #f2f2f2!important;
        }
        td {
            background: #F7F7F7!important;
            border-bottom: 0;
        }
        &::before {
            background: #F7F7F7!important;
        }
        .el-table__header-wrapper {
            border-radius: 2px 2px 0 0;
            border: 1px solid #DCDFE6;
        }
        .el-table__header th {
            height: 28px;
            line-height: 28px;
            font-size: 14px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #333333;
        }
        .el-table__body-wrapper {
            padding-top: 12px;
            background: #F7F7F7;
        }
    }
    .el-table.standard-task-edit__table.gradient {
        .el-table__header-wrapper {
            border: 0;
            border-bottom: 1px solid #DCDFE6;
        }
    }
}
.standard-task-edit-preview {
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;
    box-sizing: border-box;
    .el-icon-close {
        cursor: pointer;
        position: absolute;
        top: 12px;
        right: 12px;
        font-size: 16px;
    }
    .qrcode-title {
        font-size: 16px;
        margin-bottom: 12px;
    }
    .qrcode-image {
        width: 180px;
        height: 180px;
        margin-bottom: 12px
    }
}
</style>
